package juc;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-02-24 23:00:00
 */
public class CasTest {

    public static Integer num01 = 0;
    public static volatile Integer num02 = 0;
    public static AtomicInteger num03 = new AtomicInteger();
    public static AtomicReference<Integer> num04 = new AtomicReference(0);

    public static void add01(){
        System.out.println(++num01);
    }

    public static void add02(){
        System.out.println(++num02);
    }

    public static void add03(){
        System.out.println(num03.incrementAndGet());
    }

    public static void add04(){
        System.out.println(num04.updateAndGet((x) -> {
            x++;
            return x;
        }));
    }

    public static void test01(){
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                add01();
            }).start();
        }
    }

    public static void test02(){
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                add02();
            }).start();
        }
    }

    public static void test03(){
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                add03();
            }).start();
        }
    }

    public static void test04(){
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                add04();
            }).start();
        }
    }

    public static void main(String[] args) {
//        test01();
//        test02();
        test03();
//        test04();
    }

}
